import 'dart:async';
import 'dart:math';

import 'package:amap_flutter_map_example/base_page.dart';
import 'package:amap_flutter_map_example/const_config.dart';
import 'package:amap_flutter_map_example/widgets/amap_switch_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart' as base;

class PolylineConfigDemoPage extends BasePage {
  PolylineConfigDemoPage(String title, String subTitle) : super(title, subTitle);

  @override
  Widget build(BuildContext context) {
    return _Body();
  }
}

class _Body extends StatefulWidget {
  const _Body();

  @override
  State<StatefulWidget> createState() => _State();
}

class _State extends State<_Body> {
  static final base.LatLng mapCenter = const base.LatLng(39.909187, 116.397451);

  Map<String, Polyline> _polylines = <String, Polyline>{};
  String? selectedPolylineId;

  void _onMapCreated(AMapController controller) {}

  void _add() {
    final int polylineCount = _polylines.length;

    // 创建一个简单的折线路径
    List<base.LatLng> points = [];
    for (int i = 0; i < 5; i++) {
      double lat = mapCenter.latitude + sin((polylineCount * 5 + i) * pi / 12.0) / 20.0;
      double lng = mapCenter.longitude + cos((polylineCount * 5 + i) * pi / 12.0) / 20.0;
      points.add(base.LatLng(lat, lng));
    }

    final Polyline polyline = Polyline(
      points: points,
      width: 10.0,
      color: Colors.blue,
      visible: true,
      geodesic: false,
      alpha: 1.0,
      onTap: (polylineId) => _onPolylineTapped(polylineId),
    );

    setState(() {
      _polylines[polyline.id] = polyline;
    });
  }

  void _onPolylineTapped(String polylineId) {
    print('Polyline $polylineId 被点击了');
    setState(() {
      selectedPolylineId = polylineId;
    });
  }

  void _remove() {
    final Polyline? selectedPolyline = _polylines[selectedPolylineId];
    if (selectedPolyline != null) {
      setState(() {
        _polylines.remove(selectedPolylineId);
        selectedPolylineId = null;
      });
    } else {
      print('无选中的Polyline，无法删除');
    }
  }

  void _removeAll() {
    if (_polylines.length > 0) {
      setState(() {
        _polylines.clear();
        selectedPolylineId = null;
      });
    }
  }

  void _changeColor() {
    final Polyline polyline = _polylines[selectedPolylineId]!;
    final Color currentColor = polyline.color;

    // 简单的颜色切换
    Color newColor;
    if (currentColor == Colors.blue) {
      newColor = Colors.red;
    } else if (currentColor == Colors.red) {
      newColor = Colors.green;
    } else {
      newColor = Colors.blue;
    }

    setState(() {
      _polylines[selectedPolylineId!] = polyline.copyWith(
        colorParam: newColor,
      );
    });
  }

  void _changeWidth() {
    final Polyline polyline = _polylines[selectedPolylineId]!;
    final double currentWidth = polyline.width;
    final double newWidth = currentWidth >= 20.0 ? 5.0 : currentWidth + 5.0;

    setState(() {
      _polylines[selectedPolylineId!] = polyline.copyWith(
        widthParam: newWidth,
      );
    });
  }

  void _changeAlpha() {
    final Polyline polyline = _polylines[selectedPolylineId]!;
    final double current = polyline.alpha;
    setState(() {
      _polylines[selectedPolylineId!] = polyline.copyWith(
        alphaParam: current < 0.1 ? 1.0 : current * 0.75,
      );
    });
  }

  void _toggleVisible(value) {
    final Polyline polyline = _polylines[selectedPolylineId]!;
    setState(() {
      _polylines[selectedPolylineId!] = polyline.copyWith(
        visibleParam: value,
      );
    });
  }

  void _toggleGeodesic(value) {
    final Polyline polyline = _polylines[selectedPolylineId]!;
    // 由于 copyWith 方法不支持修改 geodesic，我们需要重新创建 polyline
    final Polyline newPolyline = Polyline(
      points: polyline.points,
      width: polyline.width,
      visible: polyline.visible,
      geodesic: value,
      alpha: polyline.alpha,
      dashLineType: polyline.dashLineType,
      capType: polyline.capType,
      joinType: polyline.joinType,
      customTexture: polyline.customTexture,
      onTap: polyline.onTap,
      color: polyline.color,
    );
    newPolyline.setIdForCopy(polyline.id);

    setState(() {
      _polylines[selectedPolylineId!] = newPolyline;
    });
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final AMapWidget map = AMapWidget(
      apiKey: ConstConfig.amapApiKeys,
      onMapCreated: _onMapCreated,
      polylines: Set<Polyline>.of(_polylines.values),
    );

    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Container(
            height: MediaQuery.of(context).size.height * 0.6,
            width: MediaQuery.of(context).size.width,
            child: map,
          ),
          Expanded(
            child: SingleChildScrollView(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Column(
                        children: <Widget>[
                          TextButton(
                            child: const Text('添加折线'),
                            onPressed: _add,
                          ),
                          TextButton(
                            child: const Text('移除折线'),
                            onPressed: (selectedPolylineId == null) ? null : _remove,
                          ),
                          TextButton(
                            child: const Text('修改颜色'),
                            onPressed: (selectedPolylineId == null) ? null : _changeColor,
                          ),
                          TextButton(
                            child: const Text('修改宽度'),
                            onPressed: (selectedPolylineId == null) ? null : _changeWidth,
                          ),
                          TextButton(
                            child: const Text('修改透明度'),
                            onPressed: (selectedPolylineId == null) ? null : _changeAlpha,
                          ),
                        ],
                      ),
                      Column(
                        children: <Widget>[
                          TextButton(
                            child: const Text('全部移除'),
                            onPressed: _polylines.length > 0 ? _removeAll : null,
                          ),
                          AMapSwitchButton(
                            label: Text('显示'),
                            onSwitchChanged: (selectedPolylineId == null) ? null : _toggleVisible,
                            defaultValue: true,
                          ),
                          AMapSwitchButton(
                            label: Text('大地曲线'),
                            onSwitchChanged: (selectedPolylineId == null) ? null : _toggleGeodesic,
                            defaultValue: false,
                          ),
                        ],
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
